package com.joe.demo.chat.server.handler;

import com.joe.demo.chat.message.ChatRequestMessage;
import com.joe.demo.chat.message.ChatResponseMessage;
import com.joe.demo.chat.server.factory.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-30
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage chatRequestMessage) throws Exception {
        final String to = chatRequestMessage.getTo();
        final Channel channel = SessionFactory.getSession().getChannel(to);
        // 在线
        if (channel != null){
            channel.writeAndFlush(new ChatResponseMessage(chatRequestMessage.getFrom(), chatRequestMessage.getContent()));
        }
        // 不在线
        else {
            channelHandlerContext.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或不在线"));
        }
    }
}
